#include <iostream>
#include <stdio.h>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

#define PATH "."
#define NAME "fifo"

class Namefifo
{
public:
    Namefifo(const string &path, const string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path + '/' + _name;
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n == 0)
        {
            cout << "success make fifo" << endl;
        }
        else
        {
            ERR_EXIT("mkfifo");
        }
    }

    ~Namefifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            cout << "success unlink" << endl;
        }
        else
        {
            ERR_EXIT("unlink");
        }
    }

private:
    string _fifoname;
    string _path;
    string _name;
};

class FifoOper
{
public:
    FifoOper(const string &path, const string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + '/' + _name;
    }

    void OpenforRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd == -1)
        {
            ERR_EXIT("open");
        }
        cout << "OpenforRead success" << endl;
    }

    void OpenforWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd == -1)
        {
            ERR_EXIT("write");
        }
        cout << "OpenforWrite success" << endl;
    }

    void Read()
    {
        while (true)
        {
            char buffer[1024];
            buffer[0] = {0};
            int number = read(_fd, buffer, sizeof(buffer) - 1);
            if (number > 0)
            {
                buffer[number] = 0;
                cout << "Client say#" << buffer << endl;
            }
            else if (number == 0)
            {
                cout << "cilent quit" << endl;
                break;
            }
            else
            {
                cout << "read error" << endl;
                break;
            }
        }
    }

    void Write()
    {
        int cnt = 0;
        pid_t id = getpid();
        string message;
        while (true)
        {
            cout << "Please write#";
            getline(cin, message);
            message += (", message number: " + to_string(cnt++) + ", [" + to_string(id) + "]");
            write(_fd, message.c_str(), message.size());
        }
    }

    void Close()
    {
        if (_fd > 0)
        {
            close(_fd);
        }
    }

    ~FifoOper()
    {
    }

private:
    string _path;
    string _name;
    string _fifoname;
    int _fd;
};